package mock.controller;

import mock.ApplicationContextProvider;
import mock.DataProvider;
import mock.entity.Person;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Set;

/**
 * @author vladimirs 04.09.2013   17:40
 */

@Controller
public class PersonController {

    protected final Log logger = LogFactory.getLog(getClass());

    @RequestMapping(value = "/getrows.htm", method = RequestMethod.POST)
    public
    @ResponseBody
    String unmarshal(@RequestParam("iDisplayStart") String sStart,
                     @RequestParam("iDisplayLength") String sAmount,
                     @RequestParam("sEcho") String sEcho
    ) {

        JSONObject result = new JSONObject();
        JSONArray array = new JSONArray();

        int amount = 10;
        int start = 0;
        int echo = 0;

        if (sEcho != null) {
            echo = Integer.parseInt(sEcho);
        }

        ApplicationContext context = ApplicationContextProvider.getApplicationContext();
        DataProvider dp = (DataProvider) context.getBean("dataProvider");

        Set<Person> catalog = dp.getData();

        if (sStart != null) {
            start = Integer.parseInt(sStart);
            if (start < 0 || start > catalog.size())
                start = 0;
        }
        if (sAmount != null) {
            amount = Integer.parseInt(sAmount);
            if (amount < 10 || amount > 100)
                amount = 10;
        }
        Person[] persons = catalog.toArray(new Person[0]);

        for (int i = start; i < (start + amount > catalog.size() ? catalog.size() : start + amount); i++) {
            JSONArray ja = new JSONArray();
            ja.add(persons[i].getTitle());
            ja.add(persons[i].getArtist());
            ja.add(persons[i].getCountry());
            ja.add(persons[i].getCompany());
            ja.add(persons[i].getPrice());
            ja.add(persons[i].getYear());
            array.add(ja);
        }

        result.put("iTotalRecords", catalog.size());
        result.put("iTotalDisplayRecords", catalog.size());
        result.put("sEcho", echo);
        result.put("aaData", array);

        return result.toJSONString();
    }


}